#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <functional>
#include <pthread.h>
#include <unistd.h>

namespace MyThread
{
    //typedef void (*func_t)(const std::string& name); // 线程要执行的任务
    using func_t = std::function<void(const std::string& )>;
    
    class Thread
    {
    public:
        void Excute()
        {
            _isruning = true;
            _func(_name);
            _isruning = false;
        }
        std::string Name()
        {
            return _name;
        }
        std::string Status()
        {
            if (_isruning)
                return "running";
            else
                return "sleep";
        }

    public:
        Thread(const std::string &name, func_t func)
            : _name(name), _func(func), _isruning(true)
        {
            std::cout << name << " create..." << std::endl;
        }
        static void *threadRoutine(void *agrs)
        {
            Thread *self = static_cast<Thread *>(agrs);
            self->Excute();
            return nullptr;
        }
        void Start()
        {
            int n = ::pthread_create(&_tid, nullptr, threadRoutine, this);
            if (n != 0)
            {
                perror("pthread_create: ");
                return;
            }
        }
        void Stop()
        {
            if (_isruning)
            {
                ::pthread_cancel(_tid); // 终止线程
                _isruning = false;
                //std::cout << "thread stop" << std::endl;
            }
        }
        void Join()
        {
            pthread_join(_tid, nullptr);
            std::cout << "thread join done" << std::endl;
        }
        ~Thread()
        {
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isruning;
        func_t _func;
    };
}